
package com.eshore.ezone.service;

import com.eshore.ezone.utils.LogUtils;
import com.eshore.ezone.utils.NotificationsUtil;
import com.eshore.ezone.utils.StringUtils;
import com.eshore.ezone.webservice.ServiceConfigs;
import com.eshore.ezone.webservice.ServiceParser;

import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.text.TextUtils;

import java.io.ByteArrayInputStream;
import java.security.MessageDigest;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class AppSyncService extends IntentService {
    private LogUtils mLog = LogUtils.getLog(AppSyncService.class);

    public AppSyncService() {
        super("AppSyncService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        try {
            doSync(this);
        } catch (Exception e) {
            mLog.error(e.getMessage());
        }
    }

    private void doSync(Context context) throws Exception {
        final String jsonText = buildJsonText();
        final ArrayList<BasicNameValuePair> vpList = ServiceConfigs.getSyncValuePairs(jsonText);
        final String response = ServiceParser.doRequest(context, "app.uploadAppList", vpList, "");
        if(TextUtils.isEmpty(response)) {
            return ;
        } else {
            mLog.debug("doSync response: " + response);
        }
        
        JSONObject jsonObj = new JSONObject(response);
        if(!jsonObj.has("code")) {
            
            
            NotificationsUtil.showNotification(context, 0, 0, 0, null, "");//TODO: add rules
        }
    }

    private String buildJsonText() throws Exception {
        final PackageManager pckMan = getPackageManager();
        final List<PackageInfo> pkgInfoList = pckMan.getInstalledPackages(0);
        final JSONObject json = new JSONObject();
        final JSONObject obj = new JSONObject();
        String appIcon;
        for (PackageInfo info : pkgInfoList) {
            appIcon = StringUtils.encode(pckMan.getApplicationLabel(info.applicationInfo)
                    .toString().getBytes("utf-8"));
            obj.put("appEnv", "android");
            obj.put("appName", appIcon);
            obj.put("packageName", info.packageName);
            obj.put("packageSig", buildSig(pckMan, info));
            obj.put("packageNewVersion", info.versionCode);
        }
        json.put("objs", obj);
        return json.toString();
    }

    private String buildSig(PackageManager pckMan, PackageInfo pkgInfo) throws Exception {
        final byte[] buf = pckMan.getPackageInfo(pkgInfo.packageName,
                PackageManager.GET_SIGNATURES).signatures[0].toByteArray();
        final ByteArrayInputStream stream = new ByteArrayInputStream(buf);
        final CertificateFactory cf = CertificateFactory.getInstance("X.509");
        final Collection<?> c = cf.generateCertificates(stream);
        byte[] bg = null;
        final Map<String, byte[]> map = new HashMap<String, byte[]>();
        int index = 0;
        final Iterator<?> iterator = c.iterator();
        Certificate cert;
        while (iterator.hasNext()) {
            cert = (Certificate) iterator.next();
            bg = cert.getEncoded();
            map.put("" + index, bg);
            bg = null;
            index++;
        }
        final MessageDigest digest = MessageDigest.getInstance("sha-1");
        final StringBuilder builder = new StringBuilder();
        if (map.get("0") != null) {
            digest.update(map.get("0"));
            final byte[] digesta = digest.digest();
            for (int j = 0; j < digesta.length; j++) {
                builder.append(digesta[j]);
            }
        }
        return builder.toString();
    }
}
